package com.dz.lm.service.appLogin.impl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.dz.lm.common.exception.DaoException;
import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.util.IMessage;
import com.dz.lm.common.util.MD5Util;
import com.dz.lm.common.util.SmsSender;
import com.dz.lm.common.util.StringUtil;
import com.dz.lm.common.utils.DateUtil;
import com.dz.lm.common.utils.random.RandomUtils;
import com.dz.lm.dao.appLogin.read.SmsTempleDao;
import com.dz.lm.dao.appLogin.write.SendSmsLogDao;
import com.dz.lm.dao.compuser.write.CompUserDao;
import com.dz.lm.dao.user.read.UserDao;
import com.dz.lm.dao.userinvite.write.UserInviteDao;
import com.dz.lm.domain.compuser.CompUser;
import com.dz.lm.domain.user.SmsInfo;
import com.dz.lm.domain.user.SmsTemple;
import com.dz.lm.domain.user.SystemSet;
import com.dz.lm.domain.user.User;
import com.dz.lm.domain.userinvite.UserInvite;
import com.dz.lm.service.AbstractService;
import com.dz.lm.service.appLogin.AppLoginService;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class AppLoginServiceImpl extends AbstractService implements AppLoginService {

    public AppLoginServiceImpl() {
        System.out.println(">>>>>>>>>>>>AppLoginServiceImpl");
    }
	@Resource
	private com.dz.lm.dao.account.write.AccountDao writeAccountDao;
    @Resource(name = "readAppLoginDao")
    private com.dz.lm.dao.appLogin.read.AppLoginDao rAppLoginDao;
	@Resource(name = "writeUserInviteDao")
	private UserInviteDao writeUserInviteDao;
    @Resource(name = "writeAppLoginDao")
    private com.dz.lm.dao.appLogin.write.AppLoginDao wAppLoginDao;
    @Resource(name = "readUserDao")
	private UserDao readUserDao;
    @Resource(name = "readVersionDao")
    private com.dz.lm.dao.appLogin.read.VersionDao readVersionDao;
    
	@Resource
	private SmsTempleDao smsTempleDao;
	@Resource(name = "writeCompUserDao")
	private CompUserDao writeCompUserDao;
	
    @Override
    public SystemSet qrySystemEnvironmentCode() throws ServiceException {
    	SystemSet ss = null;
        try {
        	ss = rAppLoginDao.qrySystemEnvironmentCode();
		} catch (DaoException e) {
			new ServiceException(e.getCause());
		}
        return ss;
    }
    @Override
    public int selectByMobilePhoneCnt(String mobilePhone) throws ServiceException {
    	int cnt = 0;
        try {
        	cnt = rAppLoginDao.selectByMobilePhoneCnt(mobilePhone);
		} catch (DaoException e) {
			new ServiceException(e.getCause());
		}
        return cnt;
    }
	@Resource
    private SmsSender smsSender;
	
	@Resource
    private IMessage imessage;
    
	@Resource
    private SendSmsLogDao sendSmsLogDao;
	
	@Resource
    private com.dz.lm.dao.appLogin.read.SendSmsLogDao rSendSmsLogDao;
	
	@Resource
    private com.dz.lm.dao.user.read.MoneyBarManagerDao rMoneyBarManagerDao;
	
    @Override
    public int addNewUserInfo(Map<String, Object> userInfo) throws ServiceException {
    	User u = new User();
    	Date day = new Date();
    	u.setMobilePhone(userInfo.get("mobilePhone").toString());

		if(userInfo.get("platform").equals("Pc")) {
			try {
				u.setPassWord(userInfo.get("password").toString());
			} catch (Exception e) {
				e.printStackTrace();
			}

		}else {
			try {
				u.setPassWord(userInfo.get("password").toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
    	u.setPwdLevel(userInfo.get("pwdLevel")!=null ? userInfo.get("pwdLevel").toString() :"0");
		if(userInfo.get("platform").equals("wexin")){
			u.setAuthChannel("1");
		}else {
			u.setAuthChannel("0");

		}
    	// 0:未实名认证，1：已实名认证
    	u.setAuthFlag("0");
    	// 1：正常
    	u.setState("1");
    	u.setOpenTime(new Timestamp(day.getTime()));
    	u.setUpdateTime(new Timestamp(day.getTime()));
    	u.setPromoCode(RandomUtils.generateStringExceptO(8));
    	int cnt = 0;
    	try {
    		cnt = wAppLoginDao.addNewUserInfo(u);
			if(userInfo.get("inviteCode") != null){ //邀请码
				Map map = new HashMap();
				map.put("promoCode",userInfo.get("inviteCode").toString());
				try {
					Map user = readUserDao.qryUserPromoCode(map);
					if(user != null){
						UserInvite invite = new UserInvite();
						invite.setCreateTime( DateUtil.getTimeStr( new Date()));
						invite.setInviteUid(Integer.valueOf(user.get("userId").toString()));
						invite.setUserId(cnt);
						invite.setCode(userInfo.get("inviteCode").toString());
						writeUserInviteDao.insertSelective(invite);
					}
				} catch (DaoException e) {
					e.printStackTrace();
				}

			}
    		if(u.getUserId()>0){ //添加账户
    			if(userInfo.get("platform").equals("Pc")){
					CompUser compUser = new CompUser();
					compUser.setUserId(u.getUserId());
					compUser.setCompId(StringUtil.getInt(userInfo.get("compId"),0));
					compUser.setRoleId(StringUtil.getInt(userInfo.get("roleId"),0));
					compUser.setStatus(0);
					compUser.setCreateTime(DateUtil.getTimeStr(new Date()));
					writeCompUserDao.insertSelective(compUser);
				}
				userInfo.put("userId",u.getUserId());
				userInfo.put("property", "1");//账户性质（1：个人；2：企业）
				userInfo.put("state", "1");//状态（1 正常 2 冻结 3 注销）
				//无数据，新增一条
				writeAccountDao.addAccount(userInfo);
			}
		} catch (DaoException e) {
			new ServiceException(e.getCause());
		}
    	return cnt;
    }
    
	/**
	 * 更新用户数据（密码）
	 * @throws ServiceException 
	 **/
	public int updateUserInfo(Map<String, Object> userInfo) throws ServiceException {
		User u = new User();
    	Date day = new Date();
    	u.setMobilePhone(userInfo.get("mobilePhone").toString());
    	if(userInfo.get("password") != null){
			u.setPassWord(userInfo.get("password").toString());
		}
		if(userInfo.get("pwdLevel") != null){
			u.setPwdLevel(userInfo.get("pwdLevel").toString());
		}
		if(userInfo.get("oppenid") != null){
			u.setOppenId(userInfo.get("oppenid").toString());
		}
    	u.setUpdateTime(new Timestamp(day.getTime()));
    	int cnt = 0;
    	try {
    		cnt = wAppLoginDao.updateUserInfo(u);
		} catch (DaoException e) {
			new ServiceException(e.getCause());
		}
    	return cnt;
	}
    
    @Override
    public String sendSms(String mobilePhone) throws ServiceException {
    	String result = null;
    	try {
	    	//发送前校验内日：1. 一分钟内的发送次数；
    		//计算1分钟之前的时间戳类型的参数(60000为毫秒数)
    		long times = 60000l;
    		int count = qrySendSmsCount(mobilePhone, times);
    		if (count >= 1) {
    			result = "LM1001"; //LM1001:您的短信发送频率过高，请稍后再试
    			return result;
    		} else {
    			//2.当日已发送次数(5次)；
    			times = 24l * 60l * 60000l;
        		count = qrySendSmsCount(mobilePhone, times);
        		if (count >= 5) {//5次
        			result = "LM1002"; //LM1002:很抱歉，发送短信验证码次数超限，请您明日再试
        			return result;
        		}
    		}
	    	//查询短信模板
			SmsTemple temp = smsTempleDao.qrySmsTemple();
	    	String content = temp.getTempContent();
	    	String sub[] = content.split("#");
	    	String sign = temp.getSign();
	    	String code = RandomUtils.generateNumString(6);
	    	content = sign + sub[0] + code + sub[2];
	    	//查询当前环境为生产环境还是测试环境
			SystemSet se = rAppLoginDao.qrySystemEnvironmentCode();
			//开发环境和测试环境只校验短信验证码
			if (se != null && !"prod".equals(se.getCode())) {
				code = "111111";
				result = "0";
			} else {
		    	try {
		    		result = smsSender.sendSms(mobilePhone, content);
				} catch (Exception e) {
					e.printStackTrace();
				}
	    	}
			SmsInfo s = new SmsInfo();
			Date day = new Date();
			s.setSmsTempId(temp.getTempId());
			s.setCode(String.valueOf(code));
			s.setMobilePhone(mobilePhone);
			s.setSendTime(new Timestamp(day.getTime()));
			s.setValid("0");
	    	if ("0".equals(result)) {
	    		s.setState("0");
	    	} else {
	    		s.setState("1");
	    	}
	    	sendSmsLogDao.addSendSmsLog(s);
    	} catch(DaoException e) {
    		new ServiceException(e.getCause());
    	}
    	return result;
    }
    
    private int qrySendSmsCount(String mobilePhone, long times) throws ServiceException {
    	int count = 0;
    	Date day = new Date();
    	long beforeTenMin = day.getTime() - times;
    	Timestamp ts = new Timestamp(beforeTenMin);
    	Map<String, Object> param = new HashMap<String, Object>();
    	param.put("sendTime", ts);
    	param.put("mobilePhone", mobilePhone);
    	
    	try {
    		count = rSendSmsLogDao.qrySendSmsCount(param);
		} catch (DaoException e) {
			new ServiceException(e.getCause());
		}
    	return count;
    }
    
    public SmsInfo qrySmsInfo(String mobilePhone) throws ServiceException {
    	SmsInfo si = null;
    	//计算10分钟之前的时间戳类型的参数(600000为毫秒数)
    	Date day = new Date();
    	long beforeTenMin = day.getTime() - 600000;
    	Timestamp ts = new Timestamp(beforeTenMin);
    	Map<String, Object> param = new HashMap<String, Object>();
    	param.put("sendTime", ts);
    	param.put("mobilePhone", mobilePhone);
    	try {
    		si = rSendSmsLogDao.qrySmsInfo(param);
		} catch (DaoException e) {
			new ServiceException(e.getCause());
		}
    	return si;
    }
    
    public int updateSmsInfo(SmsInfo si) throws ServiceException {
    	int cnt = 0;
    	try {
    		cnt = sendSmsLogDao.updateSmsInfo(si);
		} catch (DaoException e) {
			new ServiceException(e.getCause());
		}
    	return cnt;
    }
    
    public Map<String, Object> qryUserInfo(Map<String, Object> qryParam) throws ServiceException {
    	Map<String, Object> user = null;
    	try {
    		user = rAppLoginDao.qryUserInfo(qryParam);
		} catch (DaoException e) {
			new ServiceException(e.getCause());
		} catch (Exception e) {
			e.getMessage();
		}
    	return user;
    }
    
    public Map<String, Object> qryRyToken(Map<String, Object> param) throws ServiceException {
    	Map<String, Object> tokenInfo = null;
    	try {
    		tokenInfo = rAppLoginDao.qryRyToken(param);
		} catch (DaoException e) {
			new ServiceException(e.getCause());
		} catch (Exception e) {
			e.getMessage();
		}
    	return tokenInfo;
    }
    
    public String getRyToken(String userId) throws ServiceException {
    	String ryToken = null;
    	try {
    		Map<String, Object> param = new HashMap<String, Object>();
    		param.put("userId", userId);
    		Map<String, Object> user = rAppLoginDao.qryUserInfoByUserId(param);
    		String loginName = user.get("loginName") != null?user.get("loginName").toString():"";
    		String profile = user.get("profile") != null?user.get("profile").toString():"";
    		ryToken = imessage.getToken(userId, loginName, profile);
    		if (ryToken != null && !"".equals(ryToken)) {
    			param.put("ryToken", ryToken);
    			int count = wAppLoginDao.updateRyToken(param);
    			if (count == 0) {
    				wAppLoginDao.addRyToken(param);
    			}
    		}
		} catch (DaoException e) {
			new ServiceException(e.getCause());
		} catch (Exception e) {
			e.getMessage();
		}
    	return ryToken;
    }
    
	/**
	 * 查询我入驻的bar列表及app最新版本信息
	 * @throws ServiceException 
	 **/
	public Map<String, Object> qryFavoriteMoneyBarList(Map<String, Object> param) throws ServiceException {
		Map<String, Object> retData = new HashMap<String, Object>();
		try {
			Map<String, Object> appVerInfo = readVersionDao.qryVersionInfo(param);
			List<Map<String, Object>> barList = rMoneyBarManagerDao.qryFavoriteMoneyBarList(param);
	    	//查询当前环境为生产环境还是测试环境
			SystemSet se = rAppLoginDao.qrySystemEnvironmentCode();
			retData.put("appVerInfo", appVerInfo);
			retData.put("barList", barList);
			retData.put("isOn", se.getIsOn());
			return retData;
		} catch (DaoException e) {
			e.printStackTrace();
		}
		return null;
	}
}
